package com.usts2022.classcostrecord;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.usts2022.classcostrecord.Utils.AlbumsUtil;
import com.usts2022.classcostrecord.Utils.CameraUtils;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.User;
import com.usts2022.classcostrecord.entity.UserViewModel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AddFragment extends Fragment {

    private static final String TAG = "addActivity";
    public static final int CHOOSE_CAMERA = 101;
    public static final int CHOOSE_CAMERA1 = 103;
    public static final int CHOOSE_PHOTO = 102;
    public static final int CHOOSE_PHOTO1 = 104;
    private TextView dateSel;
    private Date date;
    private EditText mCost,mAcceptancePerson;
    private ImageView mItemPhoto, mReceipts;
    private SimpleDateFormat simpleDateFormat;
    private Uri itemUri;
    private Button mSubmit;
    String itemPath,path;
    private User user;


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "---onActivityResult---");
        Bitmap bitmap = null;
        switch (requestCode) {
            case CHOOSE_CAMERA:
                try {
                    if (itemUri != null) {
                        bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(itemUri));
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                mItemPhoto.setImageBitmap(bitmap);
                //保存
                itemPath = CameraUtils.saveToSystemGallery(bitmap, getActivity());
                break;

            case CHOOSE_PHOTO:
                itemPath = AlbumsUtil.handImage(data, getActivity());
                if (itemPath != null) {
                    bitmap = BitmapFactory.decodeFile(itemPath);
                    mItemPhoto.setImageBitmap(bitmap);
                } else {
                    Toast.makeText(getActivity(), "修改图片失败", Toast.LENGTH_SHORT).show();
                }
                break;

            case CHOOSE_CAMERA1:
                try {
                    if (itemUri != null) {

                        bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(itemUri));
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                mReceipts.setImageBitmap(bitmap);
                //保存
                path = CameraUtils.saveToSystemGallery(bitmap, getActivity());
                break;

            case CHOOSE_PHOTO1:
                path = AlbumsUtil.handImage(data, getActivity());
                if (path != null) {
                    bitmap = BitmapFactory.decodeFile(path);
                    mReceipts.setImageBitmap(bitmap);
                } else {
                    Toast.makeText(getActivity(), "修改图片失败", Toast.LENGTH_SHORT).show();
                }
                break;


        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add, container, false);
        //时间转换器
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //获取用户信息
        UserViewModel userViewModel = new ViewModelProvider(getActivity()).get(UserViewModel.class);
        user =  userViewModel.getUser();
        //绑定
        mSubmit = view.findViewById(R.id.btn_submit);
        dateSel = view.findViewById(R.id.date_sel);
        mItemPhoto = view.findViewById(R.id.item_photo);
        mReceipts = view.findViewById(R.id.receipts);
        mCost = view.findViewById(R.id.add_cost);
        mAcceptancePerson = view.findViewById(R.id.acc_ps);

        //设置时间
        dateSel.setText(simpleDateFormat.format(new Date()));

        //点击发布事件
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String date = dateSel.getText().toString();
                String cost = mCost.getText().toString();
                String acceptancePerson = mAcceptancePerson.getText().toString();
                File itemPhotoFile = new File(itemPath);
                File shoppingReceiptsFile = new File(path);
                //请求
                String url = "/user/uploadReport";
                HttpUtils.imgPost(url, itemPhotoFile, shoppingReceiptsFile, date, cost, acceptancePerson, user.getClassCode(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Looper.prepare();
                        Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Looper.prepare();
                        if (response.code() != 200) {
                            Toast.makeText(getActivity(),"发布失败",Toast.LENGTH_SHORT).show();
                            return;
                        }else {
                            Toast.makeText(getActivity(),"发布成功",Toast.LENGTH_SHORT).show();
                            Message message = new Message();
                            message.what = 1;
                            uiHandler.sendMessage(message);
                        }
                        Looper.loop();
                    }
                });


            }
        });



        //实物照片
        mItemPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View alertView = LayoutInflater.from(getActivity()).inflate(R.layout.alert_dialog, null);
                Button mAlertCamera = alertView.findViewById(R.id.alert_camera);
                Button mAlertAlbums = alertView.findViewById(R.id.alert_albums);
                AlertDialog dialog = builder.setTitle("上传实物照片").setView(alertView).show();
                //相册点击事件
                mAlertAlbums.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlbumsUtil.isAllowedAlbums(getActivity(), AddFragment.this, CHOOSE_PHOTO);
                        dialog.dismiss();
                    }
                });

                //相机点击事件
                mAlertCamera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            itemUri = CameraUtils.isAllowedCamera(getActivity(), AddFragment.this, CHOOSE_CAMERA);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();

                    }
                });
            }
        });

        //购物小票点击事件
        mReceipts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View alertView = LayoutInflater.from(getActivity()).inflate(R.layout.alert_dialog, null);
                Button mAlertCamera = alertView.findViewById(R.id.alert_camera);
                Button mAlertAlbums = alertView.findViewById(R.id.alert_albums);
                AlertDialog dialog = builder.setTitle("上传购物小票照片").setView(alertView).show();
                //相册点击事件
                mAlertAlbums.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlbumsUtil.isAllowedAlbums(getActivity(), AddFragment.this, CHOOSE_PHOTO1);
                        dialog.dismiss();
                    }
                });

                //相机点击事件
                mAlertCamera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            itemUri = CameraUtils.isAllowedCamera(getActivity(), AddFragment.this, CHOOSE_CAMERA1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();

                    }
                });
            }
        });


        //日期选择器
        dateSel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                        String text = "你选择了：" + year + "年" + (month + 1) + "月" + dayOfMonth + "日";
                        String dateStr = year + "-" + (month + 1) + "-" + dayOfMonth;

                        try {
                            date = simpleDateFormat.parse(dateStr);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        dateSel.setText(dateStr);
                    }
                }
                        , calendar.get(Calendar.YEAR)
                        , calendar.get(Calendar.MONTH)
                        , calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        return view;


    }


    public Handler uiHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 1) {
                mCost.setText("");
                mAcceptancePerson.setText("");
                path = null;
                itemPath = null;
                Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.upload);
                mItemPhoto.setImageBitmap(bitmap);
                mReceipts.setImageBitmap(bitmap);
            }
            return false;
        }
    });


}